<template >
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索输入框和添加商品按钮 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input clearable placeholder="请输入内容" v-model="queryInfo.query" @clear="getGoodsList('search')" @keyup.enter.native="getGoodsList('search')">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList('search')"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="goAddGoodsPage">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table stripe :data="goodsList" border style="width: 100%">
        <el-table-column label="#" type="index" header-align="center" align="center"></el-table-column>
        <el-table-column label="商品名称" show-overflow-tooltip prop="goods_name"></el-table-column>
        <el-table-column label="商品数量" prop="goods_number" header-align="center" align="center" width="70"></el-table-column>
        <el-table-column label="商品价格(元)" prop="goods_price" header-align="center" align="center" width="95"></el-table-column>
        <el-table-column label="商品重量" header-align="center" align="center" prop="goods_weight" width="70"></el-table-column>
        <el-table-column label="创建时间" header-align="center" align="center" width="150">
          <template slot-scope="scope">
            {{scope.row.add_time*1000 | format('yyyy-MM-dd hh:mm:ss')}}
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="120">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditGoodsDialog(scope.row.goods_id)"></el-button>
            <!-- 删除按钮 -->
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteGoods(scope.row.goods_id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="pageSizes" :page-size="queryInfo.pagesize" :layout="layout" :total="total" background>
      </el-pagination>
    </el-card>

    <!-- 编辑商品的对话框 -->
    <el-dialog title="编辑商品" :visible.sync="editGoodsDialog" width="50%" @close="editGoodsDialogClosed">
      <el-form :model="editGoodsForm" :rules="editGoodsFormRules" ref="editGoodsFormRef" label-width="80px">
        <el-form-item label="商品名称" prop="goods_name">
          <el-input clearable v-model="editGoodsForm.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_number">
          <el-input clearable v-model="editGoodsForm.goods_number"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input clearable v-model="editGoodsForm.goods_price"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
          <el-input clearable v-model="editGoodsForm.goods_weight"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editGoodsDialog = false">取 消</el-button>
        <el-button type="primary" @click="editGoods">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 检查正数（包括小数）的数字的自定义验证规则
    const checkIsPositiveNumber = (rule, value, callback) => {
      const regNumner = /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/
      if (!regNumner.test(value)) {
        return callback(new Error('此处必须填写大于或等于0的正整数或小数'));
      } else {
        callback();
      }
    };
    // 检查正数（包括小数）的数字的自定义验证规则
    const checkIspositiveIntegerNumber = (rule, value, callback) => {
      const regNumner = /^[1-9]\d*$/
      if (!regNumner.test(value)) {
        return callback(new Error('此处必须填写大于0的正整数'));
      } else {
        callback();
      }
    };
    return {
      // 所有商品列表
      goodsList: [],
      // 获取商品列表请求体参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 商品总数量
      total: 0,
      // 分页可供选择的每页显示几条数据
      pageSizes: [5, 10, 15, 20],
      // 分页的功能项
      layout: 'total, sizes, prev, pager, next, jumper',
      // 修改商品对话框的显示隐藏控制值
      editGoodsDialog: false,
      // 修改商品对话框的表单数据对象
      editGoodsForm: {},
      // 修改商品对话框的表单数据验证规则对象
      editGoodsFormRules: {
        goods_name: [
          { required: true, message: '商品名称为必填项', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '商品数量为必填项', trigger: 'blur' },
          { validator: checkIspositiveIntegerNumber, trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '商品价格为必填项', trigger: 'blur' },
          { validator: checkIsPositiveNumber, trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '商品重量为必填项', trigger: 'blur' },
          { validator: checkIsPositiveNumber, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 发送请求获取所有的商品列表
    async getGoodsList(keywords) {
      if (keywords === 'search') {
        this.queryInfo.pagenum = 1;
        this.queryInfo.pagesize = 10;
      }
      const res = await this.$axios.get('goods', { params: this.queryInfo });
      if (res.meta.status !== 200) return this.$message.error('获取商品列表数据失败！');
      this.goodsList = res.data.goods;
      this.total = res.data.total
      // console.log(this.goodsList);
      // console.log(this.total);
    },

    // 每页显示的数据个数发生变化的事件函数
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getGoodsList();
    },

    // 页码值发生变化时的事件函数
    handleCurrentChange(newPagenum) {
      this.queryInfo.pagenum = newPagenum;
      this.getGoodsList();
    },

    // 点击删除按钮删除对应id的商品
    async deleteGoods(id) {
      // 弹出信息提示框并通过async/await 简化异步事件操作
      const confirmResult = await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);

      // console.log(confirmResult);
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除操作！');
      const res = await this.$axios.delete('goods/' + id);
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error('删除失败！');
      this.$message.success('删除成功！');
      // 为了在删除最后一页的最后一条数据时能成功跳转回最后一页的上一页
      const totalPage = Math.ceil((this.total - 1) / this.queryInfo.pagesize) // 总页数
      this.queryInfo.pagenum = this.queryInfo.pagenum > totalPage ? totalPage : this.queryInfo.pagenum;
      this.queryInfo.pagenum = this.queryInfo.pagenum < 1 ? 1 : this.queryInfo.pagenum;
      // 刷新商品数据列表
      this.getGoodsList();
    },

    // 显示编辑商品的对话框，并根据id查询商品
    async showEditGoodsDialog(id) {
      this.editGoodsDialog = true;
      const res = await this.$axios.get('goods/' + id);
      if (res.meta.status !== 200) return this.$message.error('获取商品信息失败！');
      this.editGoodsForm = res.data;
    },

    // 监听关闭编辑商品的对话框的事件，重置表单
    editGoodsDialogClosed() {
      this.$refs.editGoodsFormRef.resetFields();
    },

    // 提交编辑请求确定的点击事件
    editGoods() {
      // 提交表单数据预验证
      this.$refs.editGoodsFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return;
        // 验证数据通过，发起请求
        const res = await this.$axios.put('goods/' + this.editGoodsForm.goods_id, this.editGoodsForm);
        // a: {
        //   goods_name: this.editGoodsForm.goods_name,
        //     goods_price: this.editGoodsForm.goods_price,
        //       goods_number: this.editGoodsForm.goods_number,
        //         goods_weight: this.editGoodsForm.goods_weight
        // }
        // console.log(res);
        if (res.meta.status !== 200) return this.$message.error('修改商品信息失败！');
        this.$message.success('修改商品信息成功！');
        // 关闭对话框
        this.editGoodsDialog = false;
        // 刷新商品数据表格
        this.getGoodsList();
      });
    },

    // 跳转到添加商品的路由页面
    goAddGoodsPage() {
      this.$router.push('/goods/add');
    }

  },
  created() {
    this.getGoodsList();
  }
}
</script>

<style lang="less" scoped>
.el-table {
  font-size: 12px;
}
</style>
